import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { PersonnelService } from '../../../../services/personnel.service';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';
import { OrganizationService } from 'src/app/services/organization.service';
import { Md5 } from 'ts-md5';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
import { UploadService } from 'src/app/services/upload.service';
import { PersonnelInfo } from 'src/app/models';
import { UploadHeaderComponent } from '../upload-header/upload-header.component';
import { NzModalService } from 'ng-zorro-antd';
import { DepartmentService } from 'src/app/services/department.service';

@Component({
  selector: 'zepride-addemployee',
  templateUrl: './addemployee.component.html',
  styleUrls: ['./addemployee.component.less']
})
export class AddemployeeComponent implements OnInit {

  @Input() info: boolean;
  @Input() edit: any;
  userId: string;
  upstatus = false;
  seedId = '';
  departlist = [];
  loading = false;
  code = '';
  orginlist = {
    name: null
  };
  userDetail: PersonnelInfo = {
    status: '0',
    imageList: [
      {
        id: '',
        name: '身份证',
        list: [],
      },
      {
        id: '',
        name: '学历证',
        list: [],
      },
      {
        id: '',
        name: '其他证书',
        list: [],
      },
      {
        id: '',
        name: '文件',
        filename: '',
        url: ''
      }

    ],
    orgTree: {
      parentId: null,
      id: null,
    },
    acc: {
      username: null,
      password: null,
    },
  };
  photo = '';
  validateForm: FormGroup;
  flag = false;
  uploading = false;
  fileList: NzUploadFile[] = [];
  waiting = false; // 获取当前用户信息的接口的状态
  orgInfo: any = {};
  phone: '';
  pwdIsChanged = false;

  constructor(
    private fb: FormBuilder,
    private person: PersonnelService,
    private activatedRoute: ActivatedRoute,
    private message: NzMessageService,
    private msg: NzMessageService,
    public uploadService: UploadService,
    private organizationService: OrganizationService,
    private modal: NzModalService,
    private department: DepartmentService,

  ) { }

  async ngOnInit() {
    this.buildForm();
    this.getOrgInfo();

    const id = this.activatedRoute.snapshot.queryParams.id;
    if (id) {
      try {
        this.waiting = true;
        this.userId = id;
        this.userDetail = await this.getUserdetails(id);
        this.initFormValue(this.userDetail);
      } catch (error) {
        ExceptionHandler.current.handleError(error);
      } finally {
        this.waiting = false;
      }
    } else {
      this.getemployeeNo();
    }
    this.validateForm.controls.phone.valueChanges.subscribe((value) => {
      this.phone = value;
    });
    this.getdepartlist();
    this.getorginlist();
  }

  buildForm() {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/.*\S.*/)]],
      employeeNo: ['', [Validators.required]],
      email: [''],
      telephone: [''],
      birth: ['', [Validators.required]],
      level: [''],
      departmentId: [''],
      gender: ['man'],
      position: [''],
      password: ['', [Validators.required]],
      createTime: [null, [Validators.required]],
      phone: ['', [Validators.required, Validators.pattern(/^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/)]],
      isHeadOfDepartment: [false],
      regularTime: [''],
      dateEnd: [''],
      idCard: [''],
    });
  }

  initFormValue(userDetail) {
    console.log(this.userDetail);

    this.validateForm.patchValue({
      employeeNo: userDetail.employeeNo,
      birth: userDetail.birth ? new Date(userDetail.birth) : '',
      gender: userDetail.gender,
      idCard: userDetail.idCard,
      createTime: userDetail.createTime ? new Date(userDetail.createTime) : '',
      position: userDetail.position,
      phone: userDetail.phone,
      password: userDetail.acc.password,
      email: userDetail.email,
      telephone: userDetail.telephone,
      level: userDetail.level
    });
    this.phone = userDetail.acc.username;
    if (!userDetail.departmentNode) {
      this.validateForm.controls.isHeadOfDepartment.setValue(false);
    } else if (userDetail.departmentNode.object.leaderPerson !== userDetail.id) {
      this.validateForm.controls.isHeadOfDepartment.setValue(false);
    } else if (userDetail.departmentNode.object.leaderPerson == userDetail.id) {
      this.validateForm.controls.isHeadOfDepartment.setValue(true);
    }

    if (userDetail.extends) {
      if (userDetail.extends.regularTime) {
        this.validateForm.controls.regularTime.setValue(new Date(userDetail.extends.regularTime));
      }
      if (userDetail.extends.contractEndTime) {
        this.validateForm.controls.dateEnd.setValue(new Date(userDetail.extends.contractEndTime));
      }
    }
    if (userDetail.name) {
      this.validateForm.controls.name.setValue(userDetail.name);
    }
    if (userDetail.employeeNo) {
      this.validateForm.controls.employeeNo.setValue(userDetail.employeeNo);
    }
    if (userDetail.orgTree) {
      this.validateForm.controls.departmentId.setValue(userDetail.orgTree.parentId);
    }
  }

  getOrgInfo() {
    const infoStr = localStorage.getItem('organization');
    this.orgInfo = infoStr ? JSON.parse(infoStr) : {};
  }

  submitForm(): void {
    this.validate();
    if (this.validateForm.invalid) {
      return;
    }
    const userData = this.getUserDataFromForm();
    if (this.userId) {
      this.editUser(userData);
    } else {
      this.addUser(userData);
    }
  }

  getUserDataFromForm(): PersonnelInfo {
    const userData: PersonnelInfo = {
      ...this.userDetail,
      employeeNo: this.validateForm.controls.employeeNo.value,
      position: this.validateForm.controls.position.value,
      phone: this.validateForm.controls.phone.value,
      email: this.validateForm.controls.email.value,
      name: this.validateForm.controls.name.value,
      level: this.validateForm.controls.level.value,
      idCard: this.validateForm.controls.idCard.value,
      birth: this.validateForm.controls.birth.value ? (this.validateForm.controls.birth.value as Date).getTime() : '' as any,
      createTime: this.validateForm.controls.createTime.value ? (this.validateForm.controls.createTime.value as Date).getTime() : '' as any,
      telephone: this.validateForm.controls.telephone.value,
      gender: this.validateForm.controls.gender.value,
    };
    userData.acc = {
      username: this.validateForm.controls.phone.value // 使用手机号作为用户名
    };
    const userExtendsData = {
      contractEndTime: this.validateForm.controls.dateEnd.value ? (this.validateForm.controls.dateEnd.value as Date).getTime() : '' as any,
      regularTime: this.validateForm.controls.regularTime.value ? (this.validateForm.controls.regularTime.value as Date).getTime() : '' as any
    };
    userData.extends = { ...this.userDetail.extends, ...userExtendsData };
    if (this.validateForm.controls.departmentId.value) {
      userData.orgTree = {
        parentId: this.validateForm.controls.departmentId.value
      };
    } else {
      userData.orgTree = {
        parentId: ''
      };
    }
    if (this.userDetail.acc) {
      userData.acc = { ...this.userDetail.acc, ...userData.acc };
    }

    if (this.pwdIsChanged) {
      userData.acc.password = Md5.hashStr(this.validateForm.controls.password.value) as string;
    }


    return userData;
  }

  pwdChanged() {
    this.pwdIsChanged = true;
  }

  validate() {
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  // 修改user
  async editUser(userDetail: PersonnelInfo) {
    try {
      await this.person.updateUser(userDetail);
      this.message.success('修改成功');
      this.goBack();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  // 新增user
  async addUser(userDetail: PersonnelInfo) {
    try {
      await this.person.createUser(userDetail);
      this.message.success('添加成功');
      this.goBack(userDetail);
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  // 获取user
  getUserdetails(userId: string) {
    return this.person.getUserInfoById(userId);
  }

  goBack(userDetail?) {
    if (!this.userId && userDetail && this.seedId) {
      this.saveEmployeeNo();

    }

    history.go(-1);
  }

  // 上传文件
  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const supportTypes = ['image/jpeg', 'image/png'];
      const isSupport = supportTypes.indexOf(file.type) > -1;
      if (!isSupport) {
        this.msg.error('支持的图片格式为：JPG、PNG!');
        observer.complete();
        return;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.msg.error('图片大小不能超过10M');
        observer.complete();
        return;
      }
      observer.next(isSupport && isLt10M);
      observer.complete();
    });
  }

  getImageByName(name: string) {
    return this.userDetail.imageList.find(img => img.name === name);
  }

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: NzUploadFile }, type?: string): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        this.waiting = true;
        break;
      case 'done':
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          this.loading = false;
          this.waiting = false;

          if (type) {
            const index = this.userDetail.imageList.findIndex(img => img.name === type);
            if (index > -1) {
              this.userDetail.imageList[index].url = info.file.response.fileUrl;
              const obj = {
                name: info.file.name,
                url: info.file.response.fileUrl
              };
              this.userDetail.imageList[index].list.unshift(obj);
              console.log(this.userDetail.imageList);

            }
          } else {
            this.userDetail.headerPhoto = `${info.file.response.fileUrl}`;
          }
        });
        break;
      case 'error':
        this.msg.error('网络错误');
        this.loading = false;
        this.waiting = false;
        break;
    }
  }
  // 单位信息
  async getorginlist() {
    const orgId = localStorage.getItem('orgid');
    try {
      const res = await this.organizationService.getOrganizationInfoById(orgId);
      this.orginlist = res;
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  // 部门列表
  async getdepartlist() {
    try {
      const params = {
        organizationId: this.organizationService.orgid,
        objectName: 'Department'
      };
      const data = await this.organizationService.getOrganizationTrees(params);
      this.departlist = data ? data : [];
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  handleChangefile(info: NzUploadChangeParam): void {
    if (info.file.status === 'done') {
      this.msg.success(`${info.file.name} 上传成功`);
      this.userDetail.imageList.forEach(item => {
        if (item.name == '文件') {
          item.url = info.file.response.fileUrl;
          item.filename = info.file.name;
        }
      });
    } else if (info.file.status === 'error') {
      this.msg.error(`${info.file.name} 上传失败`);
    }
  }

  // 获取工号
  async getemployeeNo() {

    try {
      const data = await this.person.getemployeeNo();
      this.validateForm.controls.employeeNo.setValue(data.code);
      this.seedId = data.seedId;
      this.code = data.code;

    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  // 保存工号
  async saveEmployeeNo() {
    try {
      await this.person.saveUseremployeeNo(this.seedId);
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  // 删除图片文件
  delFileImg(category, img) {
    this.userDetail.imageList.some(item => {
      if (item.name == category) {
        item.list = item.list.filter(item => item !== img);
        console.log(item.list);

      }
    });
  }

  // 打开上传头像
  openConfigModal() {
    const nzTitle = '上传头像';

    const modalRef = this.modal.create({
      nzTitle,
      nzClassName: 'uploadHeader',
      nzWidth: '800px',
      nzFooter: null,
      nzContent: UploadHeaderComponent,
      nzComponentParams: {
        headerImg: this.userDetail.headerPhoto
      },

      nzOnOk: (selectorComponent) => {
        console.log(selectorComponent.croppedImage);

        this.userDetail.headerPhoto = selectorComponent.croppedImage;
        this.msg.success('保存成功');
      },
      nzOnCancel: (selectorComponent) => {
      }
    });

  }


  // 文件下载
  downloadFile(fileUrl: any, fileName: any) {

    // 获取文件扩展名
    const index = fileUrl.lastIndexOf('.');
    const fileExtension = fileUrl.substring(index + 1, fileUrl.length);

    // 图片下载
    if (/^image\[jpeg|jpg|png|gif]/.test(fileExtension)) {
      const image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        const url = canvas.toDataURL(fileUrl); // 得到图片的base64编码数据
        const a = document.createElement('a'); // 生成一个a元素
        const event = new MouseEvent('click'); // 创建一个单击事件
        a.download = fileName || 'photo'; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = fileUrl;
    } else {
      this.msg.info('暂时不支持jpeg|jpg|png|gif格式以外的图片下载');
    }

  }
}


